let customerlistModule = (() => {
  let
    selectBox = $('.selectBox'),
    searchInp = $('.searchInp'),
    tableBox = $('.tableBox'),
    tbody = tableBox.find('tbody'),
    pageBox = $('.pageBox');

  let
    lx = '',
    limit = 10,
    page = 1,
    total = 0,
    totalPage = 0,
    result = null;

  // 获取数据，渲染页面
  let render_customer = async function () {
    let res = await axios.get('/customer/list', {
      params: {
        lx,
        type: selectBox.val(),
        search: searchInp.val().trim(),
        limit,
        page
      }
    });
    if (res.code) return;
    total = parseInt(res.total);
    totalPage = parseInt(res.totalPage)
    result = res.data;

    // 渲染前先清空前一次数据
    tbody.html("")
    pageBox.html("")

    // tbody列表渲染
    let str = ``;
    result.forEach(item => {
      str += `
      <tr>
				<td class="w8">${item.name}</td>
				<td class="w5">${item.sex == 0 ? '男' : '女'}</td>
				<td class="w10">${item.email}</td>
				<td class="w10">${item.phone}</td>
				<td class="w10">${item.weixin}</td>
				<td class="w10">${item.QQ}</td>
				<td class="w5">${item.type}</td>
				<td class="w8">${item.userName}</td>
				<td class="w20">${item.address}</td>
				<td class="w14" customerId="${item.id}">
					<a href="javascript:;">编辑</a>
					<a href="javascript:;">删除</a>
					<a href="javascript:;">回访记录</a>
				</td>
			</tr>
      `
      tbody.html(str)

      // pageNum分页渲染
      if (totalPage > 1) {
        let pageStr = ``;
        // 如果当前页不是第一页，就要显示上一页
        page > 1 ? pageStr += `<a href="javascript:;">上一页</a>` : null;
        pageStr += '<ul class="pageNum">'
        for (let i = 1; i <= totalPage; i++) {
          pageStr += `<li class="${i == page ? 'active' : ''}">${i}</li>`
        }
        pageStr += '</ul>'
        // 如果当前页不是最后一页，就要显示下一页
        page < totalPage ? pageStr += `<a href="javascript:;">下一页</a>` : null;
        pageBox.html(pageStr)
      }
    })
  }
  // 绑定分页监听
  let bindPageListener = function () {
    // 下拉框绑定
    selectBox.change(render_customer)

    // 搜索框绑定
    searchInp.keydown(ev => {
      if (ev.keyCode == 13) {
        render_customer()
      }
    })

    // 事件委托做页码及上下页的绑定
    pageBox.click(ev => {
      let
        target = ev.target,
        TAG = target.tagName,
        content = target.innerHTML,
        tempPage = page

      // 上下页
      if (TAG == 'A') {
        if (content == '上一页') {
          tempPage--;
        } else {
          tempPage++;
        }
      }
      // 页码
      if (TAG == 'LI') {
        tempPage = parseInt(content)
      }
      tempPage != page ? (page = tempPage, render_customer()) : null;
    })
  }
  // 绑定三个按钮，事件委托
  let bindDelegate = function () {
    tbody.click(async ev => {
      let
        target = ev.target,
        TAG = target.tagName,
        content = target.innerHTML,
        customerId = $(target.parentElement).attr('customerId');
      if (customerId) {
        if (TAG === "A") {
          if (content == '删除') {
            let flag = confirm(`确定要删除id为${customerId}客户信息吗？`)
            if (flag) {
              let res = await axios.get('/customer/delete', {
                params: {
                  customerId
                }
              });
              !res.code ? (alert('删除成功'), render_customer()) : alert('删除失败')
            }
          }
          if (content == '编辑') {
            window.location.href = `customeradd.html?customerId=${customerId}`
          }
          if (content == '回访记录') {
            window.location.href = `visit.html?customerId=${customerId}`
          }
        }
      }
    })
  }
  return {
    init() {
      // 获取传递进来的类型
      let params = window.location.href.getUrlEncodedParams();
      params.lx ? lx = params.lx : null;
      // 初始化
      render_customer()
      // 绑定分页事件，异步获取数据
      bindPageListener()
      // 绑定三个按钮，事件委托
      bindDelegate()
    }
  }
})()

customerlistModule.init()